package bid

import (
	"context"
	"gitee.com/alex_li/amazon-rpt/cmd/rpt/process/common"
	"gitee.com/alex_li/amazon-rpt/internal/db"
	"gitee.com/alex_li/amazon-rpt/internal/sdk/advertising"
	"github.com/lishimeng/go-log"
	"time"
)

func SyncSbKeywords(ctx context.Context) {
	startTime := time.Now()
	log.Info("start sync sb keywords")
	common.TravelAmazonClients(ctx, syncSbKeywordOrg)
	endTime := time.Now()
	cost := endTime.Sub(startTime)
	log.Info("sync total sp keyword done, [%f seconds]", cost.Seconds())
}

func syncSbKeywordOrg(ctx context.Context, lwa db.AmazonLwaCommon, handler *advertising.Client) {

	startTime := time.Now()
	common.TravelAmazonPageV3(0, 100, func(startIndex, count int) (respCount int, err error) {
		return syncSbKeywords(ctx, handler, startIndex, count)
	})
	endTime := time.Now()
	cost := endTime.Sub(startTime)
	log.Info("sync sp keyword done, [org:%s][%f seconds]", lwa.Name, cost.Seconds())
}

func syncSbKeywords(ctx context.Context, handler *advertising.Client, startIndex, count int) (respCount int, err error) {

	select {
	case <-ctx.Done():
		return
	default:
	}
	req := advertising.SbKeywordListV3Req{
		AmazonPagerV3: advertising.AmazonPagerV3{
			Count:      count,
			StartIndex: startIndex,
		},
	}
	req.StateFilter = "enabled"

	resp, err := handler.ListSbKeyword(req)
	if err != nil {
		log.Info(err)
		return
	}
	if len(resp.Keywords) > 0 {
		log.Info("keyword count: %d", len(resp.Keywords))
		saveKeywords("sb", resp.Keywords...)
	}
	respCount = len(resp.Keywords)
	return
}
